#include "system_parameters.h"
#include <cstdio>
#include <thread>

extern "C" {
#include "system_readings.h"
#include "timing_module.h"
}

SystemParameters::SystemParameters() {
    init_system_readings_file();
    m_payload_status.head = HEAD;
    m_payload_status.tail = TAIL;
    m_payload_status.cmd = CMDGETPAYLOADSTATUS;
    if (update_thread.joinable()) {
        thread_stop = true;
        update_thread.join();
    }
}

SystemParameters::~SystemParameters() {
    close_system_readings_file();
    thread_stop = true;
}

void SystemParameters::start_update_thread() {
    if (!update_thread.joinable()) {
        update_thread = std::thread(&SystemParameters::update_system_status_task, this);
    }
}

/*
 * 获取载荷状态指针，用于传输数据给上位机
 */
payload_status_t SystemParameters::get_payload_status() {
    // 先计算校验值
    m_payload_status.checksum =
        checksum_gen((uint8_t *)&m_payload_status.cmd,
                     sizeof(payload_status_t) - sizeof(m_payload_status.checksum) -
                         sizeof(m_payload_status.tail) - sizeof(m_payload_status.head));
    return m_payload_status;
}

void SystemParameters::set_target_signal(target_signal_def *signal) {
    m_payload_status.attenuation = signal->power;
    m_payload_status.type = signal->type;
    m_payload_status.frequency = signal->frequency;
    m_payload_status.bandwidth = signal->bandwidth;
    m_payload_status.modulation = signal->modulation;
    m_payload_status.framestructure = signal->frameStructure;
}

void SystemParameters::set_sense_config_parameters(sense_config_para_t *parameters) {
    m_payload_status.senseMode = parameters->mode;
    m_payload_status.minfrequency = parameters->minFrequency;
    m_payload_status.maxfrequency = parameters->maxFrequency;
    m_payload_status.minbandwidth = parameters->minBandwidth;
    m_payload_status.maxbandwidth = parameters->maxBandwidth;
}

void SystemParameters::set_narrowband_freq(uint32_t freq, uint16_t bandwidth, int16_t attenuation) {
    m_payload_status.frequency = freq;
    m_payload_status.bandwidth = bandwidth;
    m_payload_status.attenuation = attenuation;
}

// 读取电池信息，CPU 温度
void SystemParameters::update_system_status_task() {
    while (!thread_stop) {
        m_payload_status.battery_capacity = read_battery_capacity();
        m_payload_status.battery_voltage = read_battery_voltage();
        m_payload_status.temperature_1 = read_system_temp1();
        m_payload_status.temperature_2 = read_system_temp2();
        std::this_thread::sleep_for(std::chrono::seconds(2));
        read_gps(&m_payload_status.latitude, &m_payload_status.longitude,
                 &m_payload_status.altitude);
    }
}
